package json.gtk;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Map.Entry;

import json.gtk.TreeModelBuilder.Built;

import org.gnome.gdk.Event;
import org.gnome.gtk.CellRendererText;
import org.gnome.gtk.DataColumnString;
import org.gnome.gtk.Gtk;
import org.gnome.gtk.TreeStore;
import org.gnome.gtk.TreeView;
import org.gnome.gtk.TreeViewColumn;
import org.gnome.gtk.Widget;
import org.gnome.gtk.Window;
import org.json.simple.parser.JSONParser;

import com.google.common.io.Resources;

/**
 * A quick example that populates a {@link TreeStore} from a JSON document on
 * the classpath (or one of the test cases if you don't provide a filename) and
 * displays it in a {@link TreeView}.
 */
public final class Demo {
	public static void main(String[] args) throws Exception {
		Gtk.init(new String[0]);

		// build the model
		URL file = Resources.getResource(args.length == 0 ? "tree-model-builder/10.json" : args[0]);
		InputStream in = file.openStream();
		JSONParser parser = new JSONParser();
		TreeModelBuilder builder = new TreeModelBuilder();
		parser.parse(new InputStreamReader(in), builder);
		Built store = builder.build();
		in.close();

		// create the view
		TreeView view = new TreeView(store.store);
		for (Entry<String, DataColumnString> column : store.columns.entrySet()) {
			TreeViewColumn vertical = view.appendColumn();
			vertical.setTitle(column.getKey());
			CellRendererText renderer = new CellRendererText(vertical);
			renderer.setText(column.getValue());
		}

		// and show it in a window
		Window window = new Window();
		window.add(view);
		window.setTitle("Demo");
		window.showAll();
		window.connect(new Window.DeleteEvent() {
			public boolean onDeleteEvent(Widget source, Event event) {
				Gtk.mainQuit();
				return false;
			}
		});

		// start the (indefinite) event loop
		Gtk.main();
	}
}
